package com.company.alibaba.test;

import java.util.Stack;

public class ParseExpression {

    public static void main(String[] args) {
        String str = "4 / 4 * 2";
        double res = parse(str);
        System.out.println(res);
    }

    public static double parse(String expression){
        Stack s = toStack(expression);
        double res = calculate(s);
        return res;
    }

    private static Stack<String> toStack(String expression){
        Stack<String> stack = new Stack<>();
        int start = 0;
        for(int i = 0; i <= expression.length(); i++){
            if(i == expression.length()){
                stack.push(expression.substring(start, i));
            }else{
                char ch = expression.charAt(i);
                switch (ch){
                    case '+':
                    case '-':
                    case '*':
                    case '/':
                        String arg = expression.substring(start, i);
                        stack.push(arg);
                        start = i;
                        String op = expression.substring(start, i + 1);
                        start = i + 1;
                        stack.push(op);
                        break;
                }
            }
        }
        return stack;
    }

    private static double calculate(Stack<String> stack){
        String ele = stack.pop();
        if(stack.isEmpty()){
            return Double.parseDouble(ele);
        }
        String ele2 = stack.pop();
        String ele3 = stack.pop();
        double arg1 = Double.parseDouble(ele3);
        double arg2 = Double.parseDouble(ele);
        double res = 0.0;
        String strRes = null;
        switch (ele2){
            case "+":
                res = arg1 + arg2;
                break;
            case "-":
                res = arg1 - arg2;
                break;
            case "*":
                res = arg1 * arg2;
                break;
            case "/":
                res = arg1 / arg2;
                break;
        }
        strRes = String.valueOf(res);
        stack.push(strRes);
        return calculate(stack);
    }

}
